import 'dart:io';

/// 生成器基类
abstract class BaseGenerator {
  /// 检查文件是否存在
  static bool fileExists(String path) {
    return File(path).existsSync();
  }

  /// 创建目录（如果不存在）
  static void createDirectoryIfNotExists(String path) {
    final directory = Directory(path);
    if (!directory.existsSync()) {
      directory.createSync(recursive: true);
      print('📁 创建目录: $path');
    }
  }

  /// 写入文件
  static void writeFile(String path, String content, {bool force = false}) {
    if (!force && fileExists(path)) {
      print('⚠️  文件已存在: $path');
      stdout.write('是否覆盖? (y/N): ');
      final input = stdin.readLineSync()?.toLowerCase();
      if (input != 'y' && input != 'yes') {
        print('❌ 跳过创建文件');
        return;
      }
    }

    File(path).writeAsStringSync(content);
    print('✅ 创建文件: $path');
  }

  /// 转换为Pascal命名法 (UserProfile)
  static String toPascalCase(String text) {
    return text
        .split(RegExp(r'[_\-\s]+'))
        .map((word) => word.isNotEmpty ? 
            '${word[0].toUpperCase()}${word.substring(1).toLowerCase()}' : '')
        .join('');
  }

  /// 转换为camel命名法 (userProfile)
  static String toCamelCase(String text) {
    final pascal = toPascalCase(text);
    return pascal.isNotEmpty ? 
        '${pascal[0].toLowerCase()}${pascal.substring(1)}' : '';
  }

  /// 转换为snake命名法 (user_profile)
  static String toSnakeCase(String text) {
    return text
        .replaceAllMapped(RegExp(r'[A-Z]'), (match) => '_${match.group(0)!.toLowerCase()}')
        .replaceAll(RegExp(r'^_'), '')
        .replaceAll(RegExp(r'[_\-\s]+'), '_')
        .toLowerCase();
  }

  /// 转换为kebab命名法 (user-profile)
  static String toKebabCase(String text) {
    return toSnakeCase(text).replaceAll('_', '-');
  }

  /// 获取模块路径
  static String getModulePath(String? module) {
    if (module == null || module.isEmpty) {
      return 'lib/shared';
    }
    return 'lib/features/${toSnakeCase(module)}';
  }

  /// 获取当前项目根路径
  static String getProjectRoot() {
    var current = Directory.current;
    while (!File('${current.path}/pubspec.yaml').existsSync()) {
      final parent = current.parent;
      if (parent.path == current.path) {
        throw Exception('未找到Flutter项目根目录');
      }
      current = parent;
    }
    return current.path;
  }

  /// 添加导入到路由文件
  static void addRouteImport(String importPath) {
    final routePath = '${getProjectRoot()}/lib/config/routes.dart';
    final routeFile = File(routePath);
    
    if (!routeFile.existsSync()) {
      print('⚠️  路由文件不存在: $routePath');
      return;
    }

    final content = routeFile.readAsStringSync();
    final importStatement = "import '$importPath';";
    
    if (content.contains(importStatement)) {
      return; // 已经存在导入
    }

    // 在最后一个import后添加新的import
    final lines = content.split('\n');
    int lastImportIndex = -1;
    
    for (int i = 0; i < lines.length; i++) {
      if (lines[i].trim().startsWith('import ')) {
        lastImportIndex = i;
      }
    }
    
    if (lastImportIndex != -1) {
      lines.insert(lastImportIndex + 1, importStatement);
      routeFile.writeAsStringSync(lines.join('\n'));
      print('📝 添加路由导入: $importStatement');
    }
  }

  /// 生成文件头部注释
  static String generateFileHeader(String fileName, String description) {
    final now = DateTime.now();
    return '''// $fileName
// $description
// Generated by Flutter脚手架工具 on ${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}

''';
  }

  /// 验证名称格式
  static bool isValidName(String name) {
    return RegExp(r'^[a-zA-Z][a-zA-Z0-9_]*$').hasMatch(name);
  }

  /// 打印成功消息
  static void printSuccess(String type, String name, String path) {
    print('\n🎉 成功创建$type: $name');
    print('📍 位置: $path');
  }

  /// 打印警告消息
  static void printWarning(String message) {
    print('⚠️  $message');
  }

  /// 打印错误消息
  static void printError(String message) {
    print('❌ $message');
  }
}